<?php

namespace app\api\controller\yexam;

use app\admin\model\yexam\ComboCategory;
use app\admin\model\yexam\ExamPapersUser;
use app\admin\model\yexam\ExamUser;
use app\admin\model\yexam\PaperBag;
use app\admin\model\yexam\SubjectCombo;
use app\admin\model\yexam\UserCombo;
use app\common\controller\Api;

/**
 * @ApiSector (考试相关接口)
 * @ApiInternal
 */
class Exam extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = [];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 获取模拟考试列表
     */
    public function virtual()
    {
        $subject_id = $this->request->post('subject_id');
        $page = $this->request->post('page');
        $limit = $this->request->post('limit');

        $examModel = new \addons\yexam\service\Exam();
        $data = $examModel->getExamList(['status'=>1,'type'=>2,
            'subject_id'=>$subject_id,
            'start_date'=>['elt',date("Y-m-d H:i:s",time())],
            'end_date'=>['egt',date("Y-m-d H:i:s",time())]
        ],$page,$limit);

        foreach ($data['data'] as &$v){
            $v['is_allow'] = 1;
        }

        $this->success('请求成功', $data);
    }

    /**
     * 获取正式考试列表
     */
    public function index()
    {
        $subject_id = $this->request->post('subject_id');
        $page = $this->request->post('page');
        $limit = $this->request->post('limit');

        $examModel = new \addons\yexam\service\Exam();
        $data = $examModel->getExamList(['status'=>1,'type'=>1,'subject_id'=>$subject_id, 'start_date'=>['elt',date("Y-m-d H:i:s",time())],
            'end_date'=>['egt',date("Y-m-d H:i:s",time())]],$page,$limit);

        foreach($data['data'] as &$v){
            //查看是否已经参加考试了
            $examUserModel = new ExamUser();
            if($examUserModel->where(['exam_id'=>$v['id'],'user_id'=>$this->auth->id,'up_status'=>2])->find()){
                $v['is_allow'] = 0;
            }else{
                $v['is_allow'] = 1;
            }
        }
        $this->success('请求成功', $data);
    }

    /**
     * 获取考试答题卡
     */
    public function card(){
        $exam_id = $this->request->post('exam_id');

        $exam = new \addons\yexam\service\Exam();
        $data = $exam->getCard($exam_id,$this->auth->id);
        if($data){
            $this->success('请求成功', $data);
        }else{
            $this->error($exam->error);
        }

    }

    /**
     * 获取考试记录
     */
    public function record(){
        $subject_id = $this->request->post('subject_id');
        $page = $this->request->post('page');
        $limit = $this->request->post('limit');

        $exam = new \addons\yexam\service\Exam();
        $data = $exam->getRecordList($subject_id,$this->auth->id,$page,$limit);

        $this->success('请求成功', $data);
    }

    /**
     * 定位到上次考试答题位置
     */
    public function position(){
        $exam_id = $this->request->post('exam_id');
        $unit = new \addons\yexam\service\Exam();
        $this->success('请求成功',$unit->getLastPosition($exam_id,$this->auth->id));
    }

    /**
     * @ApiTitle (获取考试题目详情)
     * @ApiMethod (POST)
     * @ApiParams (name=exam_id,type=integer,required=true,description=试卷id)
     * @ApiParams (name=question_id,type=integer,required=true,description=试题id)
     * @ApiHeaders (name=token,type=string,required=true,description=token)
     * @throws \think\Exception
     */
    public function question(){
        $exam_id = $this->request->post('exam_id');
        $question_id = $this->request->post('question_id');
        $question = new \addons\yexam\service\Exam();
        $data = $question->getQuestion($exam_id,$question_id,$this->auth->id);
        if($data){
            $this->success('请求成功',$data);
        }else{
            $this->error($question->error);
        }
    }

    /**
     * 开始考试
     */
    public function begin(){
        $exam_id = $this->request->post('exam_id');

        $exam = new \addons\yexam\service\Exam();
        $result = $exam->begin($exam_id,$this->auth->id);
        if($result){
            $this->success('请求成功',['endtime'=>$result]);
        }else{
            $this->error($exam->error);
        }
    }

    /**
     * @ApiTitle (考试答题)
     * @ApiMethod (POST)
     */
    public function answer(){
        $exam_id = $this->request->post('exam_id');
        $question_id = $this->request->post('question_id');
        $answer = $this->request->post('answer');
        $exam = new \addons\yexam\service\Exam();
        $result = $exam->answer($exam_id,$this->auth->id,$question_id,$answer);
        if($result){
            $this->success('请求成功');
        }else{
            $this->error($exam->error);
        }
    }

    /**
     * 交卷
     */
    public function up(){
        $exam_id = $this->request->post('exam_id');

        $exam = new \addons\yexam\service\Exam();
        $result = $exam->up($exam_id,$this->auth->id);
        if($result){
            $this->success($result);
        }else{
            $this->error($exam->error);
        }
    }

    /**
     * 错题记录
     */
    public function error_log(){
        $type = $this->request->post("type",1);
        $subject_id = $this->request->post("subject_id",0);
        $page = $this->request->post("page");
        $limit = $this->request->post("limit");
        $unit = new \addons\yexam\service\Exam();
        if(empty($subject_id)){
            $this->error('科目ID异常');
        }
        $data = $unit->getErrorLogList($subject_id,$type,$this->auth->id,$page,$limit);
        $this->success('请求成功',$data);
    }

    /**
     * 获取考试错题答题卡
     */
    public function error_card()
    {
        $exam_user_id = $this->request->post('exam_user_id');

        $subject = new \addons\yexam\service\Exam();
        $data = $subject->getErrorCard($exam_user_id,$this->auth->id);

        $this->success('请求成功', $data);
    }
    //====================== 获取试卷包  ================
    public function getPaperBag()
    {
        $subjectId = $this->request->param('subject_id');
        $type = $this->request->param('type','simulation');
        $comboSubject = new SubjectCombo();
        $comboSubjectBagList = $comboSubject->where('subject_id',$subjectId)->select();
        $userComboModel = new UserCombo();
        $userBuy = [];
        $userComboList = $userComboModel->where('user_id',$this->auth->id)->whereTime('invalid_time','>',time())->select();
        foreach ($userComboList as $buy)
        {
            array_push($userBuy,$buy['pay_comboid']);
        }
        $list = [];
        $bagLists = [];
        foreach ($comboSubjectBagList as $key => $value)
        {
            $relation = json_decode($value['combo_relation'],true);
            if ($relation[$type] != '')
            {
                if (!in_array($value['combo_id'],$userBuy)) continue;
                foreach (explode(',',$relation[$type]) as $v)
                {
                    array_push($bagLists,$v);
                }
            }
        }
        $bagLists = array_unique($bagLists);
        $paperBagModel = new PaperBag();
        $paperBagList = $paperBagModel->where('id','in',$bagLists)->select();
        if ($type == 'history')
        {
            $paperBagList = $paperBagModel->where('paper_type',4)->where('subject_id',$subjectId)->select();
        }
        foreach ($paperBagList as $bag)
        {
            $testNum = count(explode(',',$bag['papers']));
            $list[] = [
                'name' => $bag['paper_name'],
                'total_num' => $testNum,
                'scale' => $testNum,
                'test_num' => 0,
                'id' => $bag['id']
            ];
        }
        $this->success('',$list);
    }

    /**
     * @ApiTitle (随机组卷)
     * @ApiParams (name=subject_id,type=integer,required=true,description=科目id)
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function randMake()
    {
        $subjectId = $this->request->param('subject_id',0);// 科目id
        if ($subjectId == 0) $this->error('科目id错误');
        //===========获取科目分类 ===========
        $subject = new \app\admin\model\yexam\Subject();
        $cateId = $subject->where('id',$subjectId)->value('question_category_id');
        if ($cateId == 0) $this->error('请联系管理员设置题型');
        $category = new ComboCategory();
        $extend = $category->where('category_id',$cateId)->value('extend');
        if (is_null($extend)) $this->error('该科目题型未设置');
        $number = 0; // 题型数量
        $code = [];// 题型代码
        $sumScore = 0;
        $where = [];
        $question = new \app\admin\model\yexam\Question();
        foreach (json_decode($extend,true) as $key => $value)
        {
            $code[$key] = $value['score'];
            $number += $value['number']; // 该代码对应的题型数量
            array_push($where,$key);
            $sumScore += $value['score'];
        }
        if ($number == 0) $number = 100;
        $result = $question->where('questiontype','in',$where)->field('id,questiontype')->orderRaw("rand()")->limit($number)->select();
        $extend_score = [];
        $question_ids = [];
        foreach ($result as $v)
        {
            $extend_score[$v['id']] = $code[$v['questiontype']];//==== 试题对应的分数
            array_push($question_ids,$v['id']);
        }

        $paperUser = new ExamPapersUser();
        $paperUser->save([
            'subject_id' => $subjectId,
            'user_id' => $this->auth->id,
            'exam_name' => date('Y-m-d').'随机组卷',
            'total_score' => $sumScore,
            'add_time' => time(),
            'question_ids' => implode(',',$question_ids),
            'extend_score' => json_encode($extend_score)
        ]);
        $this->success('组卷成功',implode(',',$question_ids));
    }

    /**
     * @ApiTitle (套餐包含)
     * @ApiMethod (POST)
     * @ApiParams (name=subject_id,type=integer,required=true,description=科目id)
     * @ApiParams (name=type,type=integer,required=true,description=套餐类型)
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function includeCombo()
    {
        //============= 检测用户是否购买了套餐  =============
        $uid = $this->auth->id;
        $userCombo = new UserCombo();
        $subjectId = $this->request->param('subject_id');//========   科目id
        $type = $this->request->param('type');//===================  套餐类型
        $combo = new SubjectCombo();
        $lists = $combo->where('subject_id',$subjectId)->select();
        $tmpArray = [];
        $includeComboId = []; //===== 包含该类型的套餐id
        foreach ($lists as $key => $value)
        {
            $result = json_decode($value['combo_relation'],true);
            if (strlen($result[$type]) != 0)
            {
                $tmpArray[] = $value['combo_name'];
                array_push($includeComboId,$value['combo_id']);
            }
        }
        $isBuyCombo = $userCombo->where('user_id',$uid)->where('pay_comboid','in',$includeComboId)->where('subject_id',$subjectId)->find();
        if (is_null($isBuyCombo))//===== 未购买任何的套餐
            $this->error('请购买套餐',implode(',',$tmpArray),-1);
        //======== 购买了套餐检查是否过期
        if (strtotime($isBuyCombo['invalid_time']) < time())
            $this->error("套餐已过期",implode(',',$tmpArray),-1);
        $comboName = ''; // 购买的套餐名称
        $this->success('',$comboName);
    }

    /**
     * @ApiTitle (获取试卷包中的试卷列表)
     * @ApiParams (name=id,type=integer,required=true,description=试卷包id)
     * @ApiParams (name=bagType,type=integer,required=true,description=试卷包类型)
     * @throws \think\exception\DbException
     */
    public function getBagList(){
        $bagId = $this->request->param('id');//==== 试卷包id
        $bagType = $this->request->param('bagType');
        $paper = new PaperBag();
        $papers = $paper->where('id',$bagId)->value('papers');
        $tmp = [];
        foreach (array_filter(explode(',',$papers)) as $key => $value)
        {
            if ($bagType == "history")
            {
                $library = \app\admin\model\yexam\Library::get($value);
                $tmp[] = [
                    'name' => $library->library_name,
                    'scale' => 1,
                    'test_num' => 0,
                    'total_num' => count(array_filter(explode(',',$library->question_ids))),
                    'id' => $library->question_ids,
                    'keyId' => $library->id,
                ];
            }else{
                $exam = \app\admin\model\yexam\Exam::get($value);
                $tmp[] = [
                    'name' => $exam->exam_name, // 试卷名称
                    'scale' => 1, // 正确率
                    'test_num' => 0, // 已答题数
                    'total_num' => count(array_filter(explode(',',$exam->question_ids))), //试题总数
                    'id' => $exam->id,
                ];
            }
        }
        $this->success('',$tmp);
    }

    /**
     * @ApiTitle (获取试卷中的试题)
     * @ApiMethod (POST)
     * @ApiSummary (type可取值为：bag->表示是试卷包,quesion->查看试卷包下面的试题)
     * @ApiParams (name=type,type=type,required=true,description=试卷类型)
     * @ApiParams (name=bagId,type=integer,required=true,description=试卷包id)
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getQuestionList()
    {
        $type = $this->request->param('type','bag');
        if ($type == 'bag')
        {
            $bagId = $this->request->param('bagId');
            $exam = \app\admin\model\yexam\Exam::get($bagId);
            if (is_null($exam->question_ids)){
                $this->error('请联系老师添加试题');
            }
            $id = $exam->question_ids;
        }elseif ($type == 'question')
        {
            $id = $this->request->param('id');
        }
        $question = new \app\admin\model\yexam\Question();
        $list = $question->where('id','in',$id)->select();
        $tmp = [];
        //1是错 2是对 3是未答过此题
        foreach ($list as $value)
        {
            $tmp[] = [
                'id' => $value->id,
                'state' => 3
            ];
        }
        $this->success('',$tmp);
    }
}
